<template>
  <el-form label-width="100px">
    <el-form-item label="SKU名称">
      <el-input placeholder="SKU名称" v-model="skuParams.skuName" />
    </el-form-item>
    <el-form-item label="价格(元)">
      <el-input
        type="number"
        placeholder="价格(元)"
        v-model="skuParams.price"
      />
    </el-form-item>
    <el-form-item label="重量(g)">
      <el-input
        type="number"
        placeholder="重量(g)"
        v-model="skuParams.weight"
      />
    </el-form-item>
    <el-form-item label="SKU描述">
      <el-input
        type="textarea"
        placeholder="SKU描述"
        v-model="skuParams.skuDesc"
      />
    </el-form-item>
    <el-form-item label="平台属性">
      <el-form :inline="true">
        <el-form-item
          :label="item.attrName"
          v-for="item in attrData"
          :key="item.id"
        >
          <el-select
            placeholder="请选择"
            style="width: 180px"
            v-model="item.attrIdAndValueId"
          >
            <el-option
              v-for="attrValue in item.attrValueList"
              :value="`${item.id}:${attrValue.id}`"
              :label="attrValue.valueName"
              :key="attrValue.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="销售属性">
      <el-form :inline="true">
        <el-form-item
          v-for="item in saleAttr"
          :label="item.saleAttrName"
          :key="item.id"
        >
          <el-select
            placeholder="请选择"
            style="width: 180px"
            v-model="item.saleIdAndValueId"
          >
            <el-option
              v-for="saleValue in item.spuSaleAttrValueList"
              :label="saleValue.saleAttrValueName"
              :value="`${item.id}:${saleValue.id}`"
              :key="saleValue.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="图片名称">
      <!-- table组件 -->
      <el-table border :data="imgAttr" ref="table">
        <el-table-column
          type="selection"
          width="80"
          align="center"
        ></el-table-column>
        <el-table-column label="图片">
          <template #="{ row, $index }">
            <el-image
              :src="row.imgUrl"
              style="width: 100px; height: 100px"
              v-model="skuParams.skuDefaultImg"
            />
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imgName"></el-table-column>
        <el-table-column label="操作">
          <template #="{ row, $index }">
            <el-button type="primary" size="small" @click="selectImg(row)"
              >默认操作</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="saveSkuData">保存</el-button>
      <el-button type="primary" @click="cancle">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { defineOptions, reactive, ref } from "vue";
//引入仓库
import useCategoryStore from "@/store/modules/category";
import { reqAttr } from "@/api/product/attr";
import {
  reqSpuHasSale,
  reqSpuImage,
  reqAddSkuData,
  reqSkuData,
} from "@/api/product/spu";
import type {
  SaleAttrValue,
  SpuData,
  SpuImage,
  SkuData,
} from "@/api/product/spu/type";
import type { AttrData } from "@/api/product/attr/type";
import { ElMessage } from "element-plus";
defineOptions({
  name: "SkuForm",
});
//应用分类仓库
let categoryStore = useCategoryStore();
let emit = defineEmits(["changeScene"]);
let attrData = ref<AttrData[]>([]); //储存商品属性与属性值的数组
let saleAttr = ref<SaleAttrValue[]>([]); //储存已有销售属性的数组
let imgAttr = ref<SpuImage[]>([]); //储存已有图片的数组
//SKU参数的收集
let skuParams = reactive<SkuData>({
  category3Id: "", //三级分类的ID
  spuId: "", //己有的SPU的ID
  tmId: "", //SPu品牌的ID
  skuName: "", //sku名字
  price: "", //sku价格
  weight: "", //sku重量
  skuDesc: "", //sku的描述
  skuAttrValueList: [], //平台属性的收集
  skuSaleAttrValueList: [], //销售属性
  skuDefaultImg: "", //sku图片地址
});
let table = ref(); //获取table组件的实例

//添加SKU数据
const initSkuData = async (skuData: SpuData) => {
  //清空数据
  Object.assign(skuParams, {
    category3Id: "", //三级分类的ID
    spuId: "", //己有的SPU的ID
    tmId: "", //SPu品牌的ID
    skuName: "", //sku名字
    price: "", //sku价格
    weight: "", //sku重量
    skuDesc: "", //sku的描述
    skuAttrValueList: [], //平台属性的收集
    skuSaleAttrValueList: [], //销售属性
    skuDefaultImg: "", //sku图片地址
  });
  // console.log(skuData);
  const { c1Id, c2Id, c3Id } = categoryStore; //结构分类组件中的ID
  skuParams.tmId = skuData.tmId; //SPU品牌的ID
  skuParams.spuId = skuData.id as string; //己有的SPU的ID
  skuParams.category3Id = c3Id;
  //获取商品属性与属性值的方法
  let resAttr = await reqAttr(c1Id, c2Id, c3Id);
  //获取已有销售属性的方法
  let resSale = await reqSpuHasSale(skuData.id as number);
  //获取商品图片地址的方法
  let resImg = await reqSpuImage(skuData.id as number);
  attrData.value = resAttr.data;
  saleAttr.value = resSale.data;
  imgAttr.value = resImg.data;
};

//点击默认按钮的回调
const selectImg = (row: SpuImage) => {
  // toggleRowSelection	用于多选表格，切换某一行的选中状态， 如果使用了第二个参数，则可直接设置这一行选中与否
  //排他思想 只能选择当前的 其他全部不选
  imgAttr.value.forEach((item) => {
    table.value.toggleRowSelection(item, false);
  });
  //选择当前这一行 第二个参数为是否选中状态
  table.value.toggleRowSelection(row, true);
  // console.log(row);
  skuParams.skuDefaultImg = row.imgUrl as string;
};

//保存数据的方法
const saveSkuData = async () => {
  // 收集销售属性的数据
  skuParams.skuSaleAttrValueList = saleAttr.value.reduce(
    (prev: any, current: any) => {
      if (current.saleIdAndValueId) {
        let [saleAttrId, saleAttrValueId] = current.saleIdAndValueId.split(":");
        prev.push({ saleAttrId, saleAttrValueId });
      }
      return prev;
    },
    []
  );
  //收集平台属性的数据
  skuParams.skuAttrValueList = attrData.value.reduce(
    (prev: any, current: any) => {
      if (current.attrIdAndValueId) {
        let [attrId, valueId] = current.attrIdAndValueId.split(":");
        prev.push({ attrId, valueId });
      }
      return prev;
    },
    []
  );
  // 发请求
  let result = await reqAddSkuData(skuParams);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: "SKU添加成功",
    });
    emit("changeScene", { sceneNum: 0, params: "" });
  } else {
    ElMessage({
      type: "error",
      message: "SKU添加失败",
    });
  }
};

//取消按钮的回调
const cancle = () => {
  emit("changeScene", { sceneNum: 0, params: "" });
};

//子组件暴露方法
defineExpose({
  initSkuData,
});
</script>

<style scoped></style>
